package com.jin.flashsaled.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jin.flashsaled.entity.User;
import com.jin.flashsaled.mapper.UserMapper;
import com.jin.flashsaled.result.Result;
import com.jin.flashsaled.result.ResultEnum;
import com.jin.flashsaled.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jin.flashsaled.utils.CookieUtil;
import com.jin.flashsaled.utils.MD5Util;
import com.jin.flashsaled.utils.PhoneUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static java.awt.Color.black;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 靳鹏宇
 * @since 2025-09-17
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public Result login(String username, String password, HttpServletResponse response) {



        if(!PhoneUtil.isMobile(username))
        {
            return Result.error(ResultEnum.PHONE_ERROR);
        }
        User user = userMapper.selectById(Long.valueOf(username));
        if(user==null)
        {

            return Result.error(ResultEnum.LOGIN_ERROR);
        }
        String dbpwd = MD5Util.fromPasswordToDbPassword(password,"123456");
        if(user.getPassword().equals(dbpwd) && String.valueOf(user.getId()).equals(username))
        {
            //对用户名加密生成cookie
            String jwt=MD5Util.inputPasswordToDbPassword(username,"dasdoha");

            //把cookie与对应的用户信息写入redis数据库中，3分钟过期
            redisTemplate.opsForValue().set("user:"+jwt,user, 180,TimeUnit.SECONDS);
            //把 Cookie写入response中，3 分钟过期，HttpOnly，SameSite=Lax
            CookieUtil.addCookieSameSite(response, "token", jwt, 180);

            return Result.success();
        }


        return Result.error(ResultEnum.LOGIN_ERROR);
    }

}
